package qx.hyj.petrescue.intercept;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import qx.hyj.petrescue.exception.TokenErrorException;
import qx.hyj.petrescue.util.JWTUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//@Component
public class TokenIntercept implements HandlerInterceptor {
    //静态网页由get访问，其余均由post访问
    //get请求则检查cookie中是否有token
    //如果post请求头中有token，并且不为空，则放行
    private static final Logger logger = LoggerFactory.getLogger(TokenIntercept.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = null;
        System.out.println("token拦截");
        //判断请求方法是否为get
        if ("get".equals(request.getMethod().toLowerCase())) {
            //判断请求路径是否为/index
            if ("/blogs".equals(request.getRequestURI())
                    // restful路径匹配正则
                    || Arrays.asList("[/]blog[/][0-9]+", "[/]personInfo[/][0-9]+", "[/]users[/](followers|followed)").
                    stream().filter(i -> {
                        return request.getRequestURI().matches(i);
                    }).count() > 0) {
                //获取cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    //获取名为token的cookie
                    List<Cookie> list = Arrays.stream(request.getCookies())
                            .filter(cookie -> "token".equals(cookie.getName()))
                            .collect(Collectors.toList());

                    token = list.get(0).getValue();
                } else {
                    //如果没有cookie，则返回401状态码
                    response.setStatus(401);
                    response.getWriter().write("there is no cookie");
                    System.err.println("there is no cookie");
                    return false;
                }
            }
        } else {
            //获取请求头中的token
            token = request.getHeader("token");
            System.out.println("token:" + token);
            if (token == null) {
                //获取cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    //获取名为token的cookie
                    List<Cookie> list = Arrays.stream(request.getCookies())
                            .filter(cookie -> "token".equals(cookie.getName()))
                            .collect(Collectors.toList());

                    token = list.get(0).getValue();
                    System.out.println("token2:" + token);
                }
            }
            //如果token不为空
            if (token != null) {
                try {
                    //获取token中的用户id
                    Integer id = JWTUtil.getUserId(token);
                    //将用户id存入request中
                    request.setAttribute("id", id);  // 方便每次请求获得id
                    return true;
                } catch (TokenErrorException e) {
                    //如果token错误，则返回401状态码
                    response.setStatus(401);
                    response.getWriter().write(e.getMessage());
                    System.err.println(e.getMessage());
                    return false;
                }
            }

        }
        return false;  // 这里改为true，放行所有请求，方便调试
    }
}